import HttpStatusCodes from '@src/constants/HttpStatusCodes';
import apiPath from '@src/constants/apiPath';
import { IReq, IRes } from './types/express/misc';

function base(_: IReq, res: IRes) {
  return res.status(HttpStatusCodes.OK).json({name: 'This is epic api!'});
}

async function login(
  req: IReq<{username: string, password: string, domain: string}>,
  res: IRes,
) {
  const {username, password, domain} = req.body;

  const formData = new FormData();

  formData.append('j_username', username );
  formData.append('j_password', password );
  formData.append('_spring_security_remember_me', 'off');

  const response = await fetch(`${domain}${apiPath.EPIC.LOGIN}`, {
    method: 'post',
    body: formData,
  });

  res.header(
    'Set-Cookie',
    response.headers.get('set-cookie')?.valueOf() as string,
  );

  return res.status(HttpStatusCodes.OK).json({ login: 'successfully!' });
}

export default {
  base,
  login,
} as const;